package org.wattdepot.gdata.kukuicup.updater.energylastthirtydays;

import java.net.URL;
import java.text.DateFormat;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.gdata.kukuicup.service.GDataBatchRequest;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.GDataCronTask;
import org.wattdepot.util.tstamp.Tstamp;
import it.sauronsoftware.cron4j.TaskExecutionContext;

/**
 * Gets the energy used by a source for the current day so far and each day of the last thirty days.
 * @author Philip Johnson
 */
public class EnergyLastThirtyDaysColumnChanger extends GDataCronTask {
  
  /**
   * Creates the task that gets woken up once a day to reset the columns for this spreadsheet.
   * @param wattDepotService The WattDepot service configuration data. 
   * @param gdataService The gdata service configuration data.
   * @param spreadsheetURL The URL to the spreadsheet containing the data.
   */
  public EnergyLastThirtyDaysColumnChanger(WattDepotService wattDepotService, 
      GDataService gdataService, URL spreadsheetURL) {
    super(wattDepotService, gdataService, spreadsheetURL, null, 0, "EnergyColumnChanger", false);
  }

  /**
   * The method called once a day to update the column headers for the last thirty days.
   * @param context Ignored.
   * @throws RuntimeException If problems occur (which they shouldn't). 
   */
  @Override
  public void execute(TaskExecutionContext context) throws RuntimeException {
    System.out.format("%s Running EnergyLastThirtyDays column changer.%n", getTimestamp());
    //startWattDepotTiming();
    //stopWattDepotTiming();

    startGDataTiming();
    // Add the column headers to the spreadsheet.
    GDataBatchRequest request = new GDataBatchRequest(gdataService, spreadsheetURL);
    
    // Make the date formatter.
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
    try {
      // Do the last 31 days.
      XMLGregorianCalendar startDate = Tstamp.makeTimestamp();
      for (int i = 0; i < 31; i++) {
        XMLGregorianCalendar date = Tstamp.incrementDays(startDate, (i * -1));
        String dateString = dateFormat.format(date.toGregorianCalendar().getTime());
        request.addRequest(1, i + 3, dateString);
      }
      // Send the request.
      request.sendRequest();
    }
    catch (Exception e) {
      System.out.println("Error making batch request during EnergyLastThirtyDays column update");
      e.printStackTrace();
    }
    stopGDataTiming();
    printTaskResults("Last 30 column update", "kWh", "OK");
  }
}
